#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("TCP - 服务器");
    //创建QTcpServer对象
    m_server = new QTcpServer(this);
    //检测是否有新的连接
    connect(m_server,&QTcpServer::newConnection,this,[=]()
            {
                m_tcp = m_server->nextPendingConnection(); //获取TCP连接
                ui->m_status->setText("已连接");
                ui->records->append("成功和客户端建立了新连接");
                //客户端发送过来了数据
                connect(m_tcp,&QTcpSocket::readyRead,this,[=]()
                        {
                            //接受数据
                            QString recvMsg = m_tcp->readAll();
                            ui->records->append("客户端say:" + recvMsg);
                            ui->records->setAlignment(Qt::AlignRight);
                        });
                //客户端断开了连接
                connect(m_tcp,&QTcpSocket::disconnected,this,[=]()
                        {
                            ui->records->append("客户端已经断开了连接");
                            m_tcp->deleteLater();
                            ui->m_status->setText("已断开");
                        });

            });

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_startServer_clicked()
{
    unsigned short port = ui->port->text().toInt();
    //设置服务器监听
    m_server->listen(QHostAddress::LocalHost,port);
    ui->startServer->setEnabled(false);

}


void MainWindow::on_sendMsg_clicked()
{
    QString sendMsg = ui->msg->toPlainText();
    m_tcp->write(sendMsg.toUtf8());
    ui->records->append("服务器Say:" + sendMsg);
    ui->records->setAlignment(Qt::AlignLeft);
    ui->msg->clear();
}

